package com.dreamer.view.wxmall;
import com.dreamer.domain.comment.Comment;
import com.dreamer.domain.mall.goods.Goods;
import com.dreamer.domain.mall.goods.GoodsCategory;
import com.dreamer.domain.mall.goods.GoodsType;
import com.dreamer.domain.mall.shopcart.CartItem;
import com.dreamer.domain.mall.shopcart.ShopCart;
import com.dreamer.domain.user.AddressMy;
import com.dreamer.domain.user.Agent;
import com.dreamer.domain.user.User;
import com.dreamer.domain.wxmall.CommentDTO;
import com.dreamer.domain.wxmall.GoodsCategoryDTO;
import com.dreamer.domain.wxmall.GoodsDTO;
import com.dreamer.domain.wxmall.ShopCatDTO;
import com.dreamer.service.Comment.CommentHandler;
import com.dreamer.service.mobile.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ps.mx.otter.exception.ApplicationException;
import ps.mx.otter.exception.DataNotFoundException;
import ps.mx.otter.utils.WebUtil;
import ps.mx.otter.utils.message.Message;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

//特权商城
@Controller
@RequestMapping(value = {"/privilegedMall"})
public class PrivilegedMallController {

    private static final String VCART = "shopcart";

    private static final String TCART = "tshopcart";


    /**
     * 获取不同的Cart
     *
     * @param goodsType
     * @return
     */
    private String getCartFromType(GoodsType goodsType) {
        if (goodsType == GoodsType.MALL) {
            return VCART;
        }
        return TCART;
    }


    @Autowired
    private SystemParameterHandler systemParameterHandler;

    @Autowired
    private CategoryHandler categoryHandler;

    @Autowired
    private GoodsHandler goodsHandler;

    @Autowired
    private AgentHandler agentHandler;

    @Autowired
    private AddressMyHandler addressMyHandler;

    @Autowired
    private CommentHandler commentHandler;

    @Autowired
    private MuteUserHandler muteUserHandler;

    @Autowired
    private TransferHandler transferHandler;

    //特权商城首页
    @RequestMapping(value = "/dmz/mobile/index.json",method = RequestMethod.GET)
    @ResponseBody
    public Map mallIndex(HttpServletRequest request) {
        Map map = new HashMap();
        //首页幻灯片
        String imagses = systemParameterHandler.get("code", "16").getParamValue();
        String[] img = imagses.split("\\+");
        List imageList = new ArrayList();
        for (int i = 0 ; i <img.length ; i++ ) {
            imageList.add(i,img[i]);
        }


        //所有大类
        List<GoodsCategory> categorys = categoryHandler.getList("type", 1);
        List<GoodsCategoryDTO> categoriesDTOs = new ArrayList<>();
        for (GoodsCategory category : categorys) {
            GoodsCategoryDTO goodsCategoryDTO = new GoodsCategoryDTO();
            goodsCategoryDTO.setId(category.getId());
            goodsCategoryDTO.setName(category.getName());
            categoriesDTOs.add(goodsCategoryDTO);
        }

        //查询所有产品
        Map<String, Object> mapes = new HashedMap();
        mapes.put("goodsType", GoodsType.TEQ);
        //筛选分类
        Integer cid = null;
        for (GoodsCategoryDTO categoriesDTO : categoriesDTOs) {
            if("生殖健康".equals(categoriesDTO.getName())){
                cid = categoriesDTO.getId();
            }
        }
        mapes.put("category.id", cid); //首页首次进来默认查询生殖健康
        mapes.put("shelf", true);
        mapes.put("ASC", "order");//排序
        List<Goods> goodss = goodsHandler.getList(mapes);

        List<GoodsDTO> GoodsDTOs = new ArrayList<>();

        for (Goods goods : goodss) {
            GoodsDTO goodsDTO = new GoodsDTO();
            goodsDTO.setId(goods.getId());
            goodsDTO.setName(goods.getName());
            goodsDTO.setSpec(goods.getSpec());
            goodsDTO.setRetailPrice(goods.getRetailPrice());
            goodsDTO.setImgFile(goods.getImgFile());
            GoodsDTOs.add(goodsDTO);
        }


        map.put("images",imageList);
        map.put("categorys",categoriesDTOs);
        map.put("goodss",GoodsDTOs);
        return map;
    }

    //特权商城商品查询
    @RequestMapping(value = "/dmz/mobile/goodsQuery.json",method = RequestMethod.GET)
    @ResponseBody
    public Map goodsQuery(HttpServletRequest request, @RequestParam(required = false) Integer cid, @RequestParam(required = false) String goodsName) {
        Map map = new HashMap();
        //查询所有产品
        Map<String, Object> mapes = new HashedMap();
        mapes.put("goodsType", GoodsType.TEQ);
        //筛选分类
        if (cid != null) {
            mapes.put("category.id", cid);
        }
        mapes.put("shelf", true);
        mapes.put("ASC", "order");//排序
        List<Goods> goodss = goodsHandler.getList(mapes);
        if (goodsName != null && !goodsName.equals("")) {
            goodss = goodss.stream().filter(g -> g.getName().contains(goodsName)).collect(Collectors.toList());
        }

        List<GoodsDTO> GoodsDTOs = new ArrayList<>();

        for (Goods goods : goodss) {
            GoodsDTO goodsDTO = new GoodsDTO();
            goodsDTO.setId(goods.getId());
            goodsDTO.setName(goods.getName());
            goodsDTO.setSpec(goods.getSpec());
            goodsDTO.setRetailPrice(goods.getRetailPrice());
            goodsDTO.setImgFile(goods.getImgFile());
            GoodsDTOs.add(goodsDTO);
        }

        map.put("goodss",GoodsDTOs);
        return map;
    }

    /**
     * 特权商城产品详情接口
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "dmz/mobile/goodsDetail.json", method = RequestMethod.GET)
    public Map detail(@RequestParam Integer gid,HttpServletRequest request) {
        Map detailMap = new HashedMap();
        List list = new ArrayList();
        Goods goods = goodsHandler.get(gid);
        GoodsDTO goodsDTO = new GoodsDTO();
        goodsDTO.setId(goods.getId());
        goodsDTO.setName(goods.getName());
        goodsDTO.setSpec(goods.getSpec());
        goodsDTO.setRetailPrice(goods.getRetailPrice());
        goodsDTO.setImgFile(goods.getImgFile());
        if (goods.getDetailImg() != null) {
            for (String str : goods.getDetailImg().split(",")) {
                list.add( str);
            }
        }
        detailMap.put("goods",goodsDTO);
        List<Comment> comments = commentHandler.findByGid(0, gid, 100);
        List<CommentDTO> commentDTOList = new ArrayList<>();
        for (Comment comment : comments) {
            CommentDTO commentDTO = new CommentDTO();
            BeanUtils.copyProperties(comment,commentDTO);
            commentDTO.setAgentId(comment.getAgent().getId());
            commentDTO.setAgentName(comment.getAgent().getRealName());
            commentDTO.setHeadImage(comment.getAgent().getHeadimgurl());
            commentDTOList.add(commentDTO);
        }

        detailMap.put("comments", commentDTOList);
        detailMap.put("goods",goodsDTO);
        detailMap.put("banner",list);
        return detailMap;
    }


    //特权商城加入购物车
    @ResponseBody
    @RequestMapping(value = "/dmz/cart/put.json", method = RequestMethod.GET)
    public Map addGoodsToShopcart(
            @RequestParam("goodsId") Integer goodsId,
            @RequestParam(value = "quantity", required = false) Integer quantity,
            HttpServletRequest request) {
        Map map = new HashMap();
        try {
            /*Agent agentUser = (Agent) WebUtil.getCurrentUser(request);
            Agent agent = agentDAO.findById(agentUser.getId());*/
            Agent agent = agentHandler.get(61066); //登陆还没做,先写死登陆的代理
            Goods goods = goodsHandler.get(goodsId);
            String CART = getCartFromType(goods.getGoodsType());
            if (Objects.isNull(goods)) {
                throw new DataNotFoundException("商品不存在");
            }
            Object ob = WebUtil.getSessionAttribute(request, CART);
            Integer addQuantity = Objects.nonNull(quantity) ? quantity : 1, result;
            ShopCart cart;
            if (Objects.nonNull(ob)) {
                cart = (ShopCart) ob;
                if (quantity != null) {//put 覆盖
                    cart.removeItems(goods);
                }
            } else {
                cart = new ShopCart();
            }
            Double price = agent.getMainLevelPrice(goods).getPrice();
            //首先查看查看是否传入cid
            cart.addGoods(goods, addQuantity, price);
            WebUtil.addSessionAttribute(request, CART, cart);
            Map<Integer,CartItem> cartMap = cart.getItems();
            Set<Integer> keySet = cartMap.keySet();
            List<ShopCatDTO> list = new ArrayList<>();
            for(Integer keys:keySet){
                CartItem cartItem = cartMap.get(keys);
                ShopCatDTO shopCatDTO = new ShopCatDTO();
                shopCatDTO.setGoodsId(keys);
                shopCatDTO.setPrice(cartItem.getPrice());
                shopCatDTO.setQuantity(cartItem.getQuantity());
                GoodsDTO goodsDTO = new GoodsDTO();
                BeanUtils.copyProperties(cartItem.getGoods(),goodsDTO);
                shopCatDTO.setGoodsDTO(goodsDTO);
                list.add(shopCatDTO);
            }

            map.put("cart",list);
            map.put("success",true);
        } catch (Exception exp) {
            exp.printStackTrace();
            map.put("failed",false);
        }
        return  map;
    }


    //购物车
    @ResponseBody
    @RequestMapping("dmz/mobile/shopcart.json")
    public Map shopCartIndex(HttpServletRequest request, @RequestParam(required = false) Integer cid) {
        Map map = new HashMap();
       /* User user = (User) WebUtil.getCurrentUser(request);
        Agent agent = agentHandler.get(user.getId());*/
       /* Agent agent = agentHandler.get(61066); //登陆还没做,先写死登陆的代理
        map.put("agent",agent);
        //只有分公司才能购物
        String lv = agentHandler.getLevelName(agent);
        Boolean isVip = lv.equals(AgentLevelName.分公司.toString())||lv.equals(AgentLevelName.联盟单位.toString());
        map.put("isVip",isVip);

        if (isVip) {
            List<AddressMy> addressMies = addressMyHandler.findAddressByAgent(agent);
            map.put("addresses",addressMies);
        }*/

        //获取商品信息
        ShopCart cart = (ShopCart)WebUtil.getSessionAttribute(request,"tshopcart");
        map.put("cart",cart);
        return map;
    }


    /**转入库存
     * 代金券+进货券自动购买
     *
     * @return
     */
    @RequestMapping("/dmz/autoConfirm.json")
    @ResponseBody
    public Message transferAutoConfirm(HttpServletRequest request, String remark) {
        try {
            ShopCart cart = (ShopCart) WebUtil.getSessionAttribute(request, TCART);
            //初始化
            if (cart.getItems().isEmpty()) {
                return Message.createFailedMessage("购物车为空！");
            }
            Integer[] goodsIds = new Integer[cart.getItems().size()];
            Integer[] quantitys = new Integer[cart.getItems().size()];
            //封装赋值
            int i = 0;
            for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
                goodsIds[i] = entry.getKey();
                quantitys[i] = entry.getValue().getQuantity();
                i++;
            }
            if (goodsIds == null || goodsIds.length == 0) {
                throw new ApplicationException("未指定申请转货的货物");
            }
            User user = (User) WebUtil.getCurrentUser(request);
            Agent fromAgent = muteUserHandler.getMuteUser();

            //扣钱转货操作
            transferHandler.transferAutoConfirm(fromAgent.getId(), user.getId(), goodsIds, quantitys, remark,null);
            WebUtil.removeSessionAttribute(request, TCART);
            return Message.createSuccessMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.createFailedMessage(e.getMessage());
        }
    }

    /**直接发货
     * 代金券+进货券自动购买
     *
     * @return
     */
    @RequestMapping("/dmz/delivery.json")
    @ResponseBody
    public Message delivery(AddressMy address, HttpServletRequest request, String remark) {
        try {
            ShopCart cart = (ShopCart) WebUtil.getSessionAttribute(request, TCART);
            //初始化
            if (cart.getItems().isEmpty()) {
                return Message.createFailedMessage("购物车为空！");
            }
            Integer[] goodsIds = new Integer[cart.getItems().size()];
            Integer[] quantitys = new Integer[cart.getItems().size()];
            //封装赋值
            int i = 0;
            for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
                goodsIds[i] = entry.getKey();
                quantitys[i] = entry.getValue().getQuantity();
                i++;
            }
            if (goodsIds == null || goodsIds.length == 0) {
                throw new ApplicationException("未指定申请转货的货物");
            }
            User user = (User) WebUtil.getCurrentUser(request);
            Agent fromAgent = muteUserHandler.getMuteUser();

            //扣钱转货操作 发货
            transferHandler.transferAutoConfirmAndDelivery(address, fromAgent.getId(), user.getId(), goodsIds, quantitys, remark);
            WebUtil.removeSessionAttribute(request, TCART);
            return Message.createSuccessMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return Message.createFailedMessage(e.getMessage());
        }
    }
}
